package com.java.study.boot;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yuansheng.xu
 */
@SpringBootApplication
public class CloudProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudProviderApplication.class, args);
    }


    @RestController
    public static class TestController {

        @Value("${server.port}")
        String port;

        @Autowired
        ConfigurableEnvironment environment;


        @Autowired
        ObjectMapper om;

        @RequestMapping("hello")
        public Object hello(HttpServletRequest request, JsonTestDo jsonTestDo) {
            List<JSONObject> collect = Stream.of("key", "app-dev", "app", "app-", "ext-0", "ext-1", "shared-0", "shared-1")
                    .map(k -> {
                        String property = environment.getProperty(k);
                        return new JSONObject().fluentPut(k, property);
                    }).collect(Collectors.toList());
            return JSON.toJSONString(collect);
        }

        @RequestMapping("header")
        public String header(HttpServletRequest request) {
            Enumeration<String> headerNames = request.getHeaderNames();
            StringJoiner stringJoiner = new StringJoiner(",");
            while (headerNames.hasMoreElements()) {
                String s = headerNames.nextElement();
                stringJoiner.add(s);
            }
            return "all header names" + stringJoiner.toString();
        }
    }
}
